package jp.dodododo.dao.handler.impl;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import jp.dodododo.dao.IterationCallback;
import jp.dodododo.dao.columns.ResultSetColumn;
import jp.dodododo.dao.handler.ResultSetHandler;

/**
 * 
 * @author Satoshi Kimura
 */
public abstract class AbstractResultSetHandler<T> implements ResultSetHandler<T> {
	private IterationCallback<T> callback;

	public AbstractResultSetHandler(IterationCallback<T> callback) {
		this.callback = callback;
	}

	public void handle(ResultSet rs) throws SQLException {
		List<ResultSetColumn> resultSetColumnList = getResultSetColumnList(rs.getMetaData());
		while (rs.next()) {
			T row = createRow(rs, resultSetColumnList);
			if (row != null) {
				callback.iterate(row);
			}
		}
	}

	protected List<ResultSetColumn> getResultSetColumnList(ResultSetMetaData rsmd) throws SQLException {
		int count = rsmd.getColumnCount();
		List<ResultSetColumn> ret = new ArrayList<ResultSetColumn>(count);

		for (int i = 0; i < count; ++i) {
			String columnName = rsmd.getColumnLabel(i + 1);
			int columnType = rsmd.getColumnType(i + 1);
			ret.add(new ResultSetColumn(columnName, columnType));
		}
		return ret;
	}

	protected abstract T createRow(ResultSet rs, List<ResultSetColumn> resultSetColumnList) throws SQLException;

	protected IterationCallback<T> getIterationCallback() {
		return callback;
	}
}
